package model

import (
	"context"
	"fmt"
	"gitee.com/DonHz/simple-blog-system/util/ormx"
	"gorm.io/gorm"
	"time"
)

var (
	_all_article_field = ormx.GetGormFields(Article{})
)

type GormArticleDAO struct {
	db *gorm.DB
}

func NewArticleDAO(db *gorm.DB) *GormArticleDAO {
	return &GormArticleDAO{db: db}
}

func (dao *GormArticleDAO) GetArticleById(ctx context.Context, Id int64) (Article, error) {
	var art Article
	err:=dao.db.WithContext(ctx).Select(_all_article_field).Where("id=?", Id).First(&art).Error
	if err!=nil{
		if err!=gorm.ErrRecordNotFound {
			//logger.LogRus.Errorf("get article Id %d info failed: %v", Id, err)
		}
		return Article{}, err
	}
	return art, nil
}

func (dao *GormArticleDAO) GetArticleByUserId(ctx context.Context, Uid int64) ([]Article, error) {
	var arts []Article
	err:=dao.db.WithContext(ctx).Select("id, title").
		Where("author_id=?", Uid).Find(&arts).Error
	if err!=nil{
		if err!=gorm.ErrRecordNotFound {
			//logger.LogRus.Errorf("get article info from author_id %d failed: %v", Uid, err)
			fmt.Printf("get article info from author_id %d failed: %v", Uid, err)
		}
		return []Article{}, err
	}
	return arts, nil
}

func (dao *GormArticleDAO) UpdateArticle(ctx context.Context, article Article) error {
	if article.Id<=0 {
		return fmt.Errorf("could not update article by id %d", article.Id)
	}
	if len(article.Title)==0||len(article.Content)==0 {
		return fmt.Errorf("could not set article title or article to empty")
	}
	return dao.db.WithContext(ctx).Model(&Article{}).Where("id=?",article.Id).
		Updates(map[string]interface{}{
			"title": article.Title,
			"content": article.Content,
			"update_time": time.Now().UnixMilli(),
	}).Error
}

type Article struct {
	Id         int64          `gorm:"column:id; primaryKey, autoIncrement"`
	AuthorId   int64          `gorm:"column:author_id;index"`
	Title      string `gorm:"column:title;varchar(100)"`
	Content    string `gorm:"column:content;"`
	CreateTime int64          `gorm:"column:create_time"`
	UpdateTime int64          `gorm:"column:update_time"`
}
